package com.zy.core.data.jpa.support;

import com.zy.core.data.jpa.support.entity.BaseEntity;
import com.zy.core.data.jpa.support.repository.impl.BaseRepositoryImpl;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.support.JpaRepositoryFactory;
import org.springframework.data.jpa.repository.support.JpaRepositoryFactoryBean;
import org.springframework.data.repository.core.RepositoryInformation;
import org.springframework.data.repository.core.RepositoryMetadata;
import org.springframework.data.repository.core.support.RepositoryFactorySupport;

import javax.persistence.EntityManager;
import java.io.Serializable;

/**
 * 因为 springdata 会使用默认的RepositoryFactory来创建Repository的实现,而我们要使用自定义的
 * BaseRepositoryImpl来替代SimpleJpaRepository作为Repository接口的实现,这样才能为所有的Repository
 * 添加自定义方法
 * @param <R>
 * @param <T>
 * @param <I>
 */
public class BaseRepositoryFactoryBean<R extends JpaRepository<T, I>, T, I extends Serializable>extends
        JpaRepositoryFactoryBean<R, T, I>{

    public BaseRepositoryFactoryBean(Class<? extends R> repositoryInterface) {
        super(repositoryInterface);
    }

    @Override
    protected RepositoryFactorySupport createRepositoryFactory(EntityManager em) {
        return new MyRepositoryFactory(em);
    }

    private static class MyRepositoryFactory<T extends BaseEntity, I extends Serializable> extends JpaRepositoryFactory {

        private final EntityManager em;

        public MyRepositoryFactory(EntityManager em) {
            super(em);
            this.em = em;
        }
        @Override
        protected Object getTargetRepository(RepositoryInformation information) {
            BaseRepositoryImpl<T, I> targetRepository = new BaseRepositoryImpl<>((Class<T>) information.getDomainType(), em);
            return targetRepository;
        }



        @Override
        protected Class<?> getRepositoryBaseClass(RepositoryMetadata metadata) {
            return BaseRepositoryImpl.class;
        }
    }
}
